#include "itemmanagementwidget.h"
#include "ui_itemmanagementwidget.h"
#include "itemdialog.h"
#include "stockoperationdialog.h"
#include <QDebug>

ItemManagementWidget::ItemManagementWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::ItemManagementWidget)
{
    ui->setupUi(this);
    
    // 设置表格属性
    ui->itemTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->itemTable->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->itemTable->setAlternatingRowColors(true);
    ui->itemTable->horizontalHeader()->setStretchLastSection(true);
    
    // 设置表格列标题
    ui->itemTable->setColumnCount(5);
    QStringList headers;
    headers << "ID" << "物品名称" << "规格型号" << "库存数量" << "存放位置";
    ui->itemTable->setHorizontalHeaderLabels(headers);
    
    // 设置列宽
    ui->itemTable->setColumnWidth(0, 60);   // ID列较窄
    ui->itemTable->setColumnWidth(1, 150);  // 物品名称
    ui->itemTable->setColumnWidth(2, 120);  // 规格型号
    ui->itemTable->setColumnWidth(3, 80);   // 库存数量
    ui->itemTable->setColumnWidth(4, 150);  // 存放位置
    
    // 连接信号槽
    connect(ui->searchEdit, &QLineEdit::textChanged, this, &ItemManagementWidget::onSearchTextChanged);
    connect(ui->addItemBtn, &QPushButton::clicked, this, &ItemManagementWidget::onAddItemClicked);
    connect(ui->editItemBtn, &QPushButton::clicked, this, &ItemManagementWidget::onEditItemClicked);
    connect(ui->deleteItemBtn, &QPushButton::clicked, this, &ItemManagementWidget::onDeleteItemClicked);
    connect(ui->stockInBtn, &QPushButton::clicked, this, &ItemManagementWidget::onStockInClicked);
    connect(ui->stockOutBtn, &QPushButton::clicked, this, &ItemManagementWidget::onStockOutClicked);
    connect(ui->viewRecordsBtn, &QPushButton::clicked, this, &ItemManagementWidget::onViewRecordsClicked);
    connect(ui->itemTable, &QTableWidget::cellDoubleClicked, this, &ItemManagementWidget::onItemTableDoubleClicked);
    
    // 初始化时禁用需要选择的按钮
    ui->editItemBtn->setEnabled(false);
    ui->deleteItemBtn->setEnabled(false);
    ui->stockInBtn->setEnabled(false);
    ui->stockOutBtn->setEnabled(false);
    
    // 监听表格选择变化
    connect(ui->itemTable, &QTableWidget::itemSelectionChanged, this, [this]() {
        bool hasSelection = ui->itemTable->currentRow() >= 0;
        ui->editItemBtn->setEnabled(hasSelection);
        ui->deleteItemBtn->setEnabled(hasSelection);
        ui->stockInBtn->setEnabled(hasSelection);
        ui->stockOutBtn->setEnabled(hasSelection);
    });
}

ItemManagementWidget::~ItemManagementWidget()
{
    delete ui;
}

// 设置当前用户信息
void ItemManagementWidget::setCurrentUser(const UserInfo& userInfo)
{
    m_currentUser = userInfo;
}

// 刷新物品列表
void ItemManagementWidget::refreshItemList()
{
    DatabaseManager& dbManager = DatabaseManager::getInstance();
    m_allItems = dbManager.getAllItems();
    
    if (ui->searchEdit->text().isEmpty()) {
        loadItemsToTable(m_allItems);
    } else {
        onSearchTextChanged();
    }
    
    updateStatistics();
}

// 加载物品数据到表格
void ItemManagementWidget::loadItemsToTable(const QList<ItemInfo>& items)
{
    ui->itemTable->setRowCount(items.size());
    
    for (int i = 0; i < items.size(); ++i) {
        const ItemInfo& item = items[i];
        
        // ID
        QTableWidgetItem* idItem = new QTableWidgetItem(QString::number(item.id));
        idItem->setTextAlignment(Qt::AlignCenter);
        idItem->setFlags(idItem->flags() & ~Qt::ItemIsEditable);
        ui->itemTable->setItem(i, 0, idItem);
        
        // 物品名称
        QTableWidgetItem* nameItem = new QTableWidgetItem(item.name);
        nameItem->setFlags(nameItem->flags() & ~Qt::ItemIsEditable);
        ui->itemTable->setItem(i, 1, nameItem);
        
        // 规格型号
        QTableWidgetItem* modelItem = new QTableWidgetItem(item.model);
        modelItem->setFlags(modelItem->flags() & ~Qt::ItemIsEditable);
        ui->itemTable->setItem(i, 2, modelItem);
        
        // 库存数量
        QTableWidgetItem* quantityItem = new QTableWidgetItem(QString::number(item.quantity));
        quantityItem->setTextAlignment(Qt::AlignCenter);
        quantityItem->setFlags(quantityItem->flags() & ~Qt::ItemIsEditable);
        
        // 库存不足时用红色显示
        if (item.quantity < 10) {
            quantityItem->setForeground(QBrush(QColor(255, 0, 0)));
            quantityItem->setFont(QFont("", -1, QFont::Bold));
        }
        ui->itemTable->setItem(i, 3, quantityItem);
        
        // 存放位置
        QTableWidgetItem* locationItem = new QTableWidgetItem(item.location);
        locationItem->setFlags(locationItem->flags() & ~Qt::ItemIsEditable);
        ui->itemTable->setItem(i, 4, locationItem);
    }
}

// 更新统计信息
void ItemManagementWidget::updateStatistics()
{
    DatabaseManager& dbManager = DatabaseManager::getInstance();
    QVariantMap stats = dbManager.getInventoryStatistics();
    
    ui->totalItemsLabel->setText(QString("总物品数: %1").arg(stats["totalItems"].toInt()));
    ui->totalQuantityLabel->setText(QString("总库存量: %1").arg(stats["totalQuantity"].toInt()));
    ui->lowStockLabel->setText(QString("低库存物品: %1").arg(stats["lowStockItems"].toInt()));
    ui->recentOpsLabel->setText(QString("近期操作: %1").arg(stats["recentOperations"].toInt()));
}

// 获取当前选中的物品
ItemInfo ItemManagementWidget::getSelectedItem()
{
    ItemInfo item;
    int currentRow = ui->itemTable->currentRow();
    
    if (currentRow >= 0 && currentRow < m_allItems.size()) {
        QTableWidgetItem* idItem = ui->itemTable->item(currentRow, 0);
        if (idItem) {
            int itemId = idItem->text().toInt();
            // 从当前显示的列表中查找
            for (const ItemInfo& currentItem : m_allItems) {
                if (currentItem.id == itemId) {
                    item = currentItem;
                    break;
                }
            }
        }
    }
    
    return item;
}

// 检查是否有选中项
bool ItemManagementWidget::hasSelection()
{
    return ui->itemTable->currentRow() >= 0;
}

// 搜索框文本变化
void ItemManagementWidget::onSearchTextChanged()
{
    QString searchText = ui->searchEdit->text().trimmed();
    
    if (searchText.isEmpty()) {
        loadItemsToTable(m_allItems);
    } else {
        DatabaseManager& dbManager = DatabaseManager::getInstance();
        QList<ItemInfo> searchResults = dbManager.searchItems(searchText);
        loadItemsToTable(searchResults);
    }
}

// 添加物品按钮点击
void ItemManagementWidget::onAddItemClicked()
{
    ItemDialog dialog(this);
    if (dialog.exec() == QDialog::Accepted) {
        refreshItemList();
    }
}

// 编辑物品按钮点击
void ItemManagementWidget::onEditItemClicked()
{
    if (!hasSelection()) {
        QMessageBox::warning(this, "警告", "请先选择要编辑的物品！");
        return;
    }
    
    ItemInfo selectedItem = getSelectedItem();
    ItemDialog dialog(this);
    dialog.setEditMode(selectedItem);
    
    if (dialog.exec() == QDialog::Accepted) {
        refreshItemList();
    }
}

// 删除物品按钮点击
void ItemManagementWidget::onDeleteItemClicked()
{
    if (!hasSelection()) {
        QMessageBox::warning(this, "警告", "请先选择要删除的物品！");
        return;
    }
    
    ItemInfo selectedItem = getSelectedItem();
    
    int ret = QMessageBox::question(this, "确认删除", 
        QString("确定要删除物品 \"%1\" 吗？\n此操作将同时删除相关的操作记录，且不可恢复！")
        .arg(selectedItem.name),
        QMessageBox::Yes | QMessageBox::No);
    
    if (ret == QMessageBox::Yes) {
        DatabaseManager& dbManager = DatabaseManager::getInstance();
        if (dbManager.deleteItem(selectedItem.id)) {
            QMessageBox::information(this, "成功", "物品删除成功！");
            refreshItemList();
        } else {
            QMessageBox::critical(this, "错误", "删除物品失败！");
        }
    }
}

// 入库按钮点击
void ItemManagementWidget::onStockInClicked()
{
    if (!hasSelection()) {
        QMessageBox::warning(this, "警告", "请先选择要入库的物品！");
        return;
    }
    
    ItemInfo selectedItem = getSelectedItem();
    StockOperationDialog dialog(this);
    dialog.setOperationType("入库");
    dialog.setSelectedItem(selectedItem);
    dialog.setCurrentUser(m_currentUser);
    
    if (dialog.exec() == QDialog::Accepted) {
        refreshItemList();
    }
}

// 出库按钮点击
void ItemManagementWidget::onStockOutClicked()
{
    if (!hasSelection()) {
        QMessageBox::warning(this, "警告", "请先选择要出库的物品！");
        return;
    }
    
    ItemInfo selectedItem = getSelectedItem();
    StockOperationDialog dialog(this);
    dialog.setOperationType("出库");
    dialog.setSelectedItem(selectedItem);
    dialog.setCurrentUser(m_currentUser);
    
    if (dialog.exec() == QDialog::Accepted) {
        refreshItemList();
    }
}

// 表格双击事件
void ItemManagementWidget::onItemTableDoubleClicked(int row, int column)
{
    Q_UNUSED(row)
    Q_UNUSED(column)
    
    // 双击编辑物品
    onEditItemClicked();
}

// 查看操作记录
void ItemManagementWidget::onViewRecordsClicked()
{
    // 发送信号到主窗口，切换到操作记录界面
    // 这里可以通过父窗口或信号槽机制来实现界面切换
    QMessageBox::information(this, "提示",
        "点击左侧菜单的操作记录可查看所有操作记录。\n"
        "如需查看特定物品的记录，请在操作记录界面使用筛选功能。");
}
